package com.game.hall;

import com.game.common.QueueEventThread;
import com.game.dubbo.LogicCenterService;
import com.game.message.Msg;
import com.game.message.connetion.ConnectionManager;
import com.game.message.messagecode.GameServerEnum;
import com.game.message.task.IAsynProcessor;
import com.game.message.task.IProcessor;
import com.game.message.task.ProcessorManager;
import com.game.message.task.QueueEvent;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

/**
 * Created by legend9999 on 2016/6/19.
 */
@Component
public class HallBiz {
	private static Logger logger = LoggerFactory.getLogger(HallBiz.class);
	@Autowired
	private ProcessorManager processorManager;
	@Autowired
	private ApplicationContext applicationContext;
	@Autowired
	private QueueEventThread queueEventThread;
	//@Autowired
	private LogicCenterService logicCenterService;
	@Autowired
	private GameServerConnectManager gameServerConnectManager;


	public void onMsg(Msg msg, ChannelHandlerContext ctx) throws Exception {
		int msgId = msg.getMsgId();
		int sId = msg.getSID();
		//IProcessor processor = processorManager.getProcess(msgId);
		Integer userId = (Integer) ctx.attr(ConnectionManager.userIdAttributeKey).get();
		Integer gameId = (Integer) ctx.attr(ConnectionManager.gameIdAttributeKey).get();
		msg.setUserId(userId);
		if (sId ==  GameServerEnum.JINHUA.id) {
			if (userId == 0) {
				throw new Exception("用户没有登录，不能进行操作，请先登录");
			}
			//转发到金花服务器
			gameServerConnectManager.sendMsg(msg, sId);
		} else if (sId == GameServerEnum.PRIMITIVE.id) {
			if (userId == 0) {
				//throw new Exception("用户没有登录，不能进行操作，请先登录");
			}
			//转发到竞技之路服务器
			gameServerConnectManager.sendMsg(msg, sId);
		} else if (sId == GameServerEnum.HALL.id) {
			//现在只有登录消息只需要在大厅处理
			IProcessor processor = processorManager.getProcess(msgId);
			if (processor instanceof IAsynProcessor) {
				processor.process(msg, ctx);
			} else {
				queueEventThread.addProcessorTask(() -> {
                    processor.process(msg,ctx);
                    return true;
                });
			}
		} else if (sId == GameServerEnum.DUBBO.id) {
			byte[] msgBytes = logicCenterService.service(SerializationUtils.serialize(msg));
			if (msgBytes != null) {
				try {
					ctx.writeAndFlush(SerializationUtils.deserialize(msgBytes));
				} catch (Exception e) {
					e.printStackTrace();
				}
				logger.info("dubbo service call,result = {}", msgBytes);
			}
		}
	}
}
